import axios, {AxiosRequestConfig} from "axios";
import {System} from 'one-code-vue'
import _ from 'lodash'
import useMenuStore from "@/store/useMenuStore";
import useUserStore from "@/store/useUserStore";
import {useRouter} from "vue-router";
import localforage from "localforage";

const hostPort = ""
const baseUrl = hostPort + "/wms_api/api"

export interface RestApiResult<T> {
    success: string,
    msg: string,
    data: T
}

export class SystemExtend extends System {

    menuStore = useMenuStore()
    userStore = useUserStore()

    constructor() {
        super();
    }

    /**
     * 获取仓库列表
     */
    getWh() {
        return axios({
            url: `${baseUrl}/pages/sys/security/Wh@getWh`,
            method: 'POST',
            headers: {
                'Content-Type': 'application/json'
            },
        });
    }

    /**
     * 登录
     */
    login(data: { whId?: string, loginName?: string, password?: string }) {
        return axios({
            url: hostPort + "/wms_api/login",
            method: 'POST',
            headers: {
                'Content-Type': 'application/json'
            },
            data: JSON.stringify(data)
        });
    }

    /**
     * 登录
     */
    logout() {
        this.menuStore.logout()
        this.userStore.logout()

        return axios({
            url: hostPort + "/wms_api/logout",
            method: 'POST',
            headers: {
                'Content-Type': 'application/json'
            },
        }).finally();
    }

    showDialog(pagePath, props) {
        if (!pagePath) {
            return
        }

        return new Promise((resolve, reject) => {
            if (typeof pagePath === 'string') {
                if (!_.startsWith(pagePath, '/src/pages')) {
                    pagePath = '/src/pages' + pagePath
                }
                const getPage = window['pages'][pagePath]
                if (typeof getPage === 'function') {
                    getPage().then(module => {
                        super.showDialog(module.default, props).then(r => {
                            resolve(r)
                        }).catch(e => {
                            reject(e)
                        })
                    })
                } else {
                    system.showErrorDialog('无法找到模块: pages[\'' + pagePath + '\']')
                    reject()
                    return
                }

            } else {
                const bizCmp = pagePath
                super.showDialog(bizCmp, props).then(r => {
                    resolve(r)
                }).catch(e => {
                    reject(e)
                })
            }
        })
    }

    /**
     * 调用后端服务
     * @param url API地址
     * @param body API参数
     */
    invokeStudio(url: string, body?: any): Promise<RestApiResult<any>> {
        if (url === 'FileManager@getMateData') {
            // 将数据缓存进 localstore
            return new Promise<RestApiResult<any>>((resolve, reject) => {
                const cacheData = window['database_meta']
                if (cacheData) {
                    resolve(cacheData)

                } else {
                    this.invokeServer(`/com/yvan/studio/${url}`, [body]).then(res => {
                        if (res[0]) {
                            localforage.setItem('DatabaseMeta', JSON.stringify(res)).finally(() => {
                            })
                        }
                        window['database_meta'] = res
                        resolve(res)
                    }).catch((e) => {
                        reject(e)
                    })
                }
            })
        }
        return this.invokeServer(`/com/yvan/studio/${url}`, [body]) as Promise<RestApiResult<any>>
    }

    invokeServer(url: string, body?: any): Promise<InvokeServerResponse<any>> {
        const cfg: AxiosRequestConfig = {
            url: baseUrl + url,
            method: 'POST',
            headers: {
                'Content-Type': 'application/json'
            },
            // validateStatus: () => true,
            data: JSON.stringify({
                args: [body],
            })
        }
        return new Promise<InvokeServerResponse<any>>((resolve, reject) => {
            axios(cfg).then(res => {
                if (res.data.success) {
                    if (typeof window['ajaxProcess'] === 'function') {
                        window['ajaxProcess'](res.data)
                    }
                    resolve(res.data)
                    return
                }
                system.showErrorDialog(res.data.msg)
                reject(res)
            }).catch((e) => {
                reject(e)
                if (e.isAxiosError) {
                    // 网络错误
                    if (e.response.status === 401) {
                        // 跳转到登录页
                        const router = useRouter()
                        router.push({name: "login"}).finally();
                        return
                    } else if (e.response?.data?.msg) {
                        system.showErrorDialog(e.response.data.msg)
                        return
                    } else if (e.response.status === 404) {
                        system.showErrorDialog('资源没找到404: ' + url)
                        return
                    } else if (e.response.status === 500) {
                        system.showErrorDialog('服务端异常: ' + e.toString())
                        return
                    }
                }
                system.showErrorDialog('服务端异常:' + e.toString())
                return
            })
        })
    }
}
